import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useLoginUserStore } from '@/stores/loginUser'
import BasicLayout from '@/layouts/BasicLayout.vue'
import HomePage from '@/views/HomePage.vue'
import UserRegisterPage from '@/views/user/UserRegisterPage.vue'
import UserLoginPage from '@/views/user/UserLoginPage.vue'
import UserManagePage from '@/views/admin/UserManagePage.vue'
import ChatPage from '@/views/ChatPage.vue'



const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: BasicLayout,
      children: [
        {
          path: '',
          name: '主页',
          component: HomePage,
        },
        {
          path: 'user/login',
          name: '用户登录',
          component: UserLoginPage,
          meta: { requiresGuest: true } // 只允许未登录用户访问
        },
        {
          path: 'user/register',
          name: '用户注册',
          component: UserRegisterPage,
          meta: { requiresGuest: true } // 只允许未登录用户访问
        },
        {
          path: 'admin/userManage',
          name: '用户管理',
          component: UserManagePage,
          meta: { requiresAuth: true, requiresAdmin: true } // 需要管理员权限
        },
        {
          path: 'chat/:id',
          name: 'ChatPage',
          component: ChatPage,
          meta: { requiresAuth: true } // 需要登录
        },

      ]
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const loginUserStore = useLoginUserStore()

  // 确保已获取用户信息
  if (!loginUserStore.loginUser.id) {
    await loginUserStore.fetchLoginUser()
  }

  const isLoggedIn = !!loginUserStore.loginUser.id
  const isAdmin = loginUserStore.loginUser.userRole === 'admin'

  // 检查是否需要登录
  if (to.meta.requiresAuth && !isLoggedIn) {
    ElMessage.warning('请先登录')
    next('/user/login')
    return
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && !isAdmin) {
    ElMessage.error('权限不足，需要管理员权限')
    next('/')
    return
  }

  // 检查是否只允许未登录用户访问（如登录、注册页面）
  if (to.meta.requiresGuest && isLoggedIn) {
    ElMessage.info('您已登录')
    next('/')
    return
  }

  next()
})

export default router
